# 数据库工具封装
# 封装的目的：
# 1.将常用的数据库操作，封装到一个方法。后续再操作数据库时候，通过调用该方法来实现
# 2.提高代码的复用性
import pymysql


class DBUtil:
    # 定义全局变量
    conn = None

    # 建立连接
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                                   password="iHRM_student_2021",
                                   database="ihrm", charset="utf8")
        return cls.conn

    # 关闭连接
    @classmethod
    def __close_db(cls):
        cls.conn.close()

    # 查询语句
    @classmethod
    def get_one(cls,sql):
        cursor = None
        result = None

        try:
            # 创建连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            result = cursor.fetchone()

        except Exception as err:
            print("查询数据库操作错误:",str(err))

        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_db()
            return result

    # 定义增删改语句
    @classmethod
    def uid_db(cls,sql):
        cursor = None
        try:
            cls.conn = cls.__connect_db()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            cls.conn.commit()
            affect_row = cls.conn.affected_rows()
            print("影响的行数=",affect_row)

        except Exception as err:
            print("查看增删改错误日志:",str(err))
            cls.conn.rollback()
        finally:
            cursor.close()
            cls.__close_db()


